package com.changgou.oauth.controller;

import com.changgou.common.entity.Result;
import com.changgou.common.entity.StatusCode;
import com.changgou.common.exception.ExceptionCast;
import com.changgou.common.model.response.user.UserCode;
import com.changgou.oauth.service.AuthService;
import com.changgou.oauth.util.AuthToken;
import com.changgou.oauth.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/oauth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Value( "${auth.clientId}" )
    private String clientId;

    @Value( "${auth.clientSecret}" )
    private String clientSecret;

    @Value( "${auth.cookieDomain}" )
    private String cookieDomain;

    @Value( "${auth.cookieMaxAge}" )
    private int cookieMaxAge;



    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    @ResponseBody
    public Result login(String username , String password, HttpServletResponse response){
        if (username == null){
            ExceptionCast.cast( UserCode.USER_LOGIN_USERNAME_ERROR );
        }
        if (password == null){
            ExceptionCast.cast( UserCode.USER_LOGIN_PASSWORD_ERROR );
        }
        AuthToken authToken = authService.login( username, password, clientId, clientSecret );

        //将jti存入cookie
        this.saveJtiCookie(authToken.getJti(),response);

        return new Result( true, StatusCode.OK,"登录成功" );

    }

    private void saveJtiCookie(String jti, HttpServletResponse response) {
        CookieUtil.addCookie( response,cookieDomain,"/","uid",jti,cookieMaxAge,false );
    }

}
